<template>
  <div class="signature">
    <el-dialog
      title="提示"
      class="signature_dialog"
      :visible.sync="centerDialogVisible"
      fullscreen>
      <el-container>
        <el-aside>
          
        </el-aside>
        <el-main>
          <div class="pdf-container">
            <div 
              v-for="(item, index) in pdfHTML"
              :key="'container'+ index" 
              class="canvas-container"
              :id="`canvas-container${index + 1}`"
            >
              <canvas 
                @mousemove="mousemove($event, index + 1)" 
                :id="`canvas${index + 1}`"
              />

              <!-- 回显 -->
              <DrawBox 
                v-for="(boxList, inde) in (item.boxLists || [])"
                :key="`boxList${inde}`"
                :type="boxList.type"
                :position="boxList.position"
              />

              <!-- 页码 -->
              <span>第{{ index + 1 }}页</span>
            </div>
          </div>
          <div class="drag">
            <div class="deagBtn">
              <div
                class="btn"
                draggable
                @dragstart="dragstart($event, 1)"
                @drag="drag($event)"
                @dragend="dragend"
              >拖拽添加</div>
              <div
                class="btn"
                draggable
                @dragstart="dragstart($event, 2)"
                @dragend="dragend"
              >拖拽添加</div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
const PDFJS = require("pdfjs-dist");
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.min");
import DrawBox from './draw.vue'

export default {
  components: {
    DrawBox
  },
  data() {
    return {
      centerDialogVisible: true,
      // pdfUrl: "",
      pdfDoc: null, // pdfjs 生成的对象
      pdfHTML: [], // pdfjs 生成的对象
      isMove: false,
      dragType: null, // 拖动时的type
      dragBoxHeight: 100, // 拖动框宽高
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init(fileUrl) {
        fileUrl = require('./ces.pdf')
        // console.log(fileUrl)
        fileUrl.url = fileUrl.default
        let _this = this;
        try {
          let fileContent = await PDFJS.getDocument(fileUrl)
          _this.pdfDoc = fileContent;
          // 处理数据
          // 请求数据
          _this.pdfHTML = Array.from(new Array(fileContent.numPages)).reduce((pre, cur, index) => {
            let obj = {
              boxLists: []
            }
            pre.push(obj)
            return pre
          }, []);


          _this.$nextTick(() => {
            _this.renderPage(fileContent.numPages);
          })
        } catch (error) {
          console.log(error)
        }
    },
    renderPage(nums) {
      for (let item = 1; item <= nums; item++) {
          // 获取页面canvas节点
          let canvas = document.getElementById(`canvas${item}`);
          // 获取上下文
          const ctx = canvas.getContext("2d");
          // 获取每一页的内容
          this.pdfDoc.getPage(item).then(page => {
              // 文件页面的视图 1倍
              const viewport = page.getViewport(1);
              // 将画布宽度设置为视图宽度
              canvas.width = viewport.width;
              canvas.height = viewport.height;

              const renderContext = {
                  canvasContext: ctx,
                  viewport: viewport
              };
              // console.log(renderContext);
              // 渲染页面内容：参数是canvas画布上下文，以及文件视图
              page.render(renderContext);
          });
      }
    },
		drag(event) {
			console.log('drag', event);
		},
    dragstart(event, type) {
      let canvas = document.createElementNS("http://www.w3.org/1999/xhtml","canvas");
      canvas.width = canvas.height = this.dragBoxHeight;

      let ctx = canvas.getContext("2d");
      ctx.lineWidth = 4;
      ctx.moveTo(0, 0);
      ctx.lineTo(50, 50);
      ctx.moveTo(0, 50);
      ctx.lineTo(50, 0);
      ctx.stroke();

      const imageContent = canvas.toDataURL('image/jpeg', 1);
      const image = new Image();
      image.src = imageContent;
      image.onload = () => {
        console.log('image2 load');
      };
      event.dataTransfer.setDragImage(image, 50, 50);
      // 开始滑动
      this.dragType = type
      this.isMove = true
    },
    // 处理边界   清除数据
    dragend() {
      // this.dragType = null
      // console.log(this.dragType)
    },
    mousemove(e, item) {
      if (!this.isMove) return
      this.isMove = false

      let canvas = document.querySelectorAll(`#canvas${item}`)[0]
      let {dragBoxHeight, dragType} = this
      let {offsetX, offsetY} = e // 放置的x y轴
      let {clientWidth, clientHeight, offsetLeft, offsetTop} = canvas // 
      let place_position_x, place_position_y;
      let boundary = dragBoxHeight / 2 // 边界
      // console.log(offsetX, offsetY, clientWidth, clientHeight, offsetLeft, offsetTop)

      place_position_x = offsetX
      place_position_y = offsetY

      if (offsetX < boundary) { // 左上角
        place_position_x = boundary
      }
      if ((clientWidth - offsetX) < boundary) {
        place_position_x = clientWidth - boundary
      }

      if (offsetY < boundary) {
        place_position_y = boundary
      }

      if ((clientHeight - offsetY) < boundary) {
        place_position_y = clientHeight - boundary
      }
      
      let data = {
        'primitive': { // 原始
          place_position_x,
          place_position_y
        },
        'echo': { // 回显
          place_position_x: place_position_x + offsetLeft - boundary,
          place_position_y: place_position_y + offsetTop - boundary
        },
        howMany: item, // 第几个
        type: dragType
      }
      this.drawGraph(data)
    },
    /**
     * 绘图
     * primitive  原始
     * echo    回显
     * howMany  第几个
     */
    drawGraph({primitive, echo, howMany, type}) {
      // let container = document.querySelector('.canvas-container')
      // console.log(container)
      console.log(primitive, echo, howMany, type)
      let addPdfitem = [...this.pdfHTML[howMany - 1].boxLists]
      let addBoxObj = {
        type,
        position: echo
      }
      addPdfitem.push(addBoxObj)
      this.$set(this.pdfHTML[howMany - 1], 'boxLists', addPdfitem)
      console.log(this.pdfHTML)
    }
  }
}
</script>

<style lang="scss" scoped>
  .signature_dialog {
    ::v-deep .el-dialog {
      max-height: 100%;
      height: 100%;
      .el-dialog__body {
        padding: 0;
        .el-container {
          height: 100%;
          .el-aside,.el-main {
            padding: 0;
            margin: 0;
          }
          .el-main {
            display: flex;
            .pdf-container {
              display: flex;
              flex-direction: column;
              width: 100%;
              height: calc(100vh - 54px);
              overflow: auto;
              background-color: #d6d6d6;
              .canvas-container {
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                margin: 0 auto;
                flex-direction: column;
                margin-bottom: 16px;
                border-top: 1px solid #000;
                // background-color: #fff;

                .signature-box {
                  position: absolute;

                  .sigin-page {
                    width: 120px;
                    height: 120px;
                  }
                  .crevice {
                    width: 20px;
                    height: 120px;
                  }
                }
              }
            }
            .drag {
              width: 20%;
              .btn {
                display: inline-block;
                padding: 5px 12px;
                margin-bottom: 0;
                font-size: 13px;
                font-weight: normal;
                line-height: 1.53846154;
                text-align: center;
                white-space: nowrap;
                vertical-align: middle;
                cursor: pointer;
                user-select: none;
                border: 1px solid transparent;
                border-radius: 4px;
                transition: .4s cubic-bezier(.175, .885, .32, 1);
                transition-property: background, border, box-shadow, outline, opacity;
                color: #353535;
                background-color: #f2f2f2;
                border-color: #bfbfbf;
                &:hover {
                  color: #353535;
                  background-color: #dedede;
                  border-color: #a1a1a1;
                  box-shadow: 0 2px 1px rgba(0, 0, 0, .1);
                }
              }
            }
          }
        }
      }
    }
  }
</style>